/*
 * MIT License
 *
 * Copyright (c) 2020 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package cn.seaboot.openapi.response;

import cn.seaboot.commons.core.CommonUtils;
import cn.seaboot.openapi.base.MethodInfo;
import cn.seaboot.postman.response.Response;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;

/**
 * 扫描 Controller 返回值，获取到 Response 的样例数据。
 * <p>
 * 这里写得还不够好，没做泛型数据分析
 *
 * @author Mr.css
 * @version 2021-01-31 14:29
 */
public class DefaultResponseAnalyzer implements ResponseAnalyzer {
    /**
     * 获取接口的样例数据
     * <p>
     * 目前的做法就是，根据返回值类型直接构造对象实例，
     * 利用 fastjson 的功能，获取数据样例。
     * <p>
     * 还有进一步优化的空间，分析带泛型的接口。
     *
     * @param method method
     * @return 字段描述
     */
    @Override
    public Response[] analyze(MethodInfo method) {
        try {
            String requestMethod = method.getRequestMethod();

            // 只有 get 请求的返回值，才有分析的价值
            if (CommonUtils.isEmpty(requestMethod) || "GET".equals(requestMethod)) {
                // 尝试构建返回值对象实例，这里写得还不够好，没做泛型数据分析
                Class<?> ret = method.getMethod().getReturnType();
                Object example = ret.newInstance();

                // 使用工具类获取返回值所有有效的成员变量
                Response result = new Response();
                result.setName("Response 样例");
                result.setBody(JSON.toJSONString(example, JSONWriter.Feature.PrettyFormat, JSONWriter.Feature.WriteMapNullValue));
                return new Response[]{result};
            }
        } catch (Exception ignore) {
            // 样例数据，并不是非常重要，如果无法解析就算了
        }
        return null;
    }
}
